<template>
	<div class="user-manage">
		<div class="community-input">
			<button v-if="store.state.userInfoX?.account" @click="addClick(),titleValue = '文件添加'">添加文件</button>
		</div>
		<div class="user-manage-table" ref="totalHeight">
			<el-table :data="tableData" :height="tbodyHeight" style="width: 100%">
				<el-table-column property="nickName" label="昵称" width="180">
				</el-table-column>
				<el-table-column align="center" property="avatar" label="头像">
					<template #default="scope">
						<div>
							<img style="width: 60px;height: 60px;object-fit: cover;"
								:src="scope.row.avatar?scope.row.avatar:require('../../assets/image/icon-defalut.png')">
						</div>
					</template>
				</el-table-column>
				<el-table-column align="center" property="file_title" label="标题">
				</el-table-column>
				<el-table-column align="center" property="file_describe" label="描述">
				</el-table-column>
				<el-table-column align="center" property="dir" label="源码">
					<template #default="scope">
						<a :href="scope.row.file_zip_url" title="点击下载源码">
							{{scope.row.dir}}
						</a>
					</template>
				</el-table-column>
				
				<el-table-column align="center" property="nickName" label="查看" width="180">
					<template #default="scope">
						<a :href="scope.row.page_url" title="点击查看生成界面">
							{{scope.row.page_url}}
						</a>
					</template>
				</el-table-column>
				<el-table-column align="center" property="create_time" label="创建时间">
					<template #default="scope">
						<div>
							{{moment(scope.row.create_time).format('YYYY-MM-DD HH:mm:ss')}}
						</div>
					</template>
				</el-table-column>
				<el-table-column align="center" property="nickName" label="是否开源" width="180">
					<template #default="scope">
						<div>
							<el-switch disabled :model-value="scope.row.file_source?true:false" />
						</div>
					</template>
				</el-table-column>
				<el-table-column width="180" align="center" property="create_time" label="操作">
					<template #default="scope">
						<el-button @click="editFileClick(scope.row),titleValue = '文件编辑'">编辑</el-button>
						<el-button @click="deleteFileClick(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>

		<el-dialog v-model="dialogFormMoneyVisible" :title="titleValue" width="500px" draggable>
			<el-form>
				<el-form-item label="标题">
					<el-input v-model="pageData.file_title" placeholder="请输入标题" />
				</el-form-item>
				<el-form-item label="描述">
					<el-input type="textarea" v-model="pageData.file_describe" placeholder="请输入描述" />
				</el-form-item>
				<el-form-item label="是否开源">
					<el-switch v-model="pageData.file_source" />
				</el-form-item>
				<el-form-item label="文件">
					<el-upload class="avatar-uploader" :on-progress="uploadEvent" action="##" :show-file-list="false"
						:http-request="httpRequestZip" :before-upload="beforeAvatarUploadZip">
						{{saveFile?.name?saveFile?.name:pageData.dir?'原：'+pageData.dir:'点击上传'}}
					</el-upload>
					<p class="progress-value" v-if="progress">{{progress}}</p>
					<p class="file-dec">
						（使用说明：上传必须上传ZIP压缩包，压缩包里有且只有一个文件夹，文件夹不可以为中文，上传完成后可查看表格里的“说明”字段使用）
					</p>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="dialogFormMoneyVisible = false">取消</el-button>
					<el-button  type="primary" @click="submitMoneyClick">确定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
	import {
		ref,
		onMounted,
		nextTick,
		inject
	} from 'vue'
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus'
	import {
		HttpPersonalList,
		HttpReviseUserPermissions,
		HttpSetUserMoney,
		HttpUpdateZip,
		HttpGetUpdateZip
	} from '../../public/http'
	import moment from 'moment'
	import bus from '../../public/bus'
	interface User {
		id: number,
			file: string,
			dir: string,
			nickName: string,
			create_time: string,
			title: string,
			describe: string,
			file_source:number|null
	}
	const store = inject('store')
	let tableData = ref < User > ([])
	const totalHeight = ref(null)
	const saveFile = ref(null)
	const dialogFormMoneyVisible = ref(false)
	const tbodyHeight = ref(null)
	let titleValue = ref(null)
	let progress = ref(false)
	let pageData = ref < User > ({
		file_title: '',
		file_describe: '',
		file_source: 0,
	})
	bus.on('progress',(value)=>{
		progress.value = value
	})
	// 用户列表
	const userMain = (page) => {
		HttpGetUpdateZip().then((res: any) => {
			if (res.code === 200) {
				tableData.value = res.data.arrange_list
			}
		})
	}
	const deleteFileClick = (row)=>{
		ElMessageBox.confirm(
		    '确定要删除此文件嘛?',
		    '提示',
		    {
		      confirmButtonText: '确定',
		      cancelButtonText: '取消',
		      type: 'warning',
		    }
		  )
		    .then(() => {
		      let formdata = new FormData()
		      formdata.append('delete_id', row.id)
		      formdata.append('file_id', row.id)
		      HttpUpdateZip('public', formdata).then((res: any) => {
		      	if (res.code === 200) {
		      		ElMessage({
		      			message: '删除成功',
		      			type: 'success',
		      		})
		      		userMain()
		      	} else {
		      		ElMessage({
		      			message: res.message,
		      			type: 'warning',
		      		})
		      	}
		      })
		    })
		    .catch(() => {
		     
		    })
		
	}
	const addClick = () => {
		saveFile.value = null
		pageData.value = {
			file_title: '',
			file_describe: '',
			file_source: 0,
		}
		dialogFormMoneyVisible.value = true
	}
	const editFileClick = (row) => {
		saveFile.value = null
		pageData.value = row
		pageData.value.file_source = row.file_source?true:false
		dialogFormMoneyVisible.value = true
		console.log(row)
	}
	// 提交
	const submitMoneyClick = () => {
		if (titleValue.value === '文件添加') {
			if (!saveFile.value) {
				ElMessage.error('文件不能为空！')
				return
			}
			console.log(pageData.value)
			let formdata = new FormData()
			formdata.append('files', saveFile.value)
			formdata.append('title', pageData.value.file_title)
			formdata.append('describe', pageData.value.file_describe)
			formdata.append('file_source', pageData.value.file_source?1:0)
			HttpUpdateZip('public', formdata,(progressEvent)=>{
				let complete = parseInt(progressEvent.loaded / progressEvent.total * 100 | 0, 10);
				progress.value = `上传进度：${complete}%`
			}).then((res: any) => {
				if (res.code === 200) {
					ElMessage({
						message: '提交成功',
						type: 'success',
					})
					dialogFormMoneyVisible.value = false
					userMain()
					progress.value = false
				}else {
					ElMessage({
						message: res.message,
						type: 'warning',
					})
					progress.value = false
				}
			})
		} else {
			let formdata = new FormData()
			formdata.append('files', saveFile.value)
			formdata.append('title', pageData.value.file_title)
			formdata.append('describe', pageData.value.file_describe)
			formdata.append('file_id', pageData.value.id)
			formdata.append('file_source', pageData.value.file_source?1:0)
			HttpUpdateZip('public', formdata,(progressEvent)=>{
				let complete = parseInt(progressEvent.loaded / progressEvent.total * 100 | 0, 10);
				progress.value = `上传进度：${complete}%`
			}).then((res: any) => {
				if (res.code === 200) {
					ElMessage({
						message: '修改成功',
						type: 'success',
					})
					dialogFormMoneyVisible.value = false
					userMain()
					progress.value = false
				} else {
					ElMessage({
						message: res.message,
						type: 'warning',
					})
					progress.value = false
				}
			})
		}
	}
	const httpRequestZip = (files: any, uploadFile: any) => {
		console.log(files.file)
		saveFile.value = files.file
	}
	const beforeAvatarUploadZip: UploadProps['beforeUpload'] = (rawFile) => {
		if (rawFile.type.indexOf('zip') === -1) {
			ElMessage.error('文件必须是zip压缩包！')
			return false
		}
		let size = rawFile.size/1024/1024
		if (size > 30) {
			ElMessage.error('上传的文件大小不能超过30MB！')
			return false
		}
		return true
	}
	const uploadEvent = (progressEvent) => { 
		console.log('进度',progressEvent);
		// let progressPercent = Number(
		//   ((progressEvent.loaded / progressEvent.total) * 100).toFixed(2)
		// );
		// // 更具需要设置显示的进度，如上传错误需要有提示信息时，要求上传进度不是100
		// this.percentage = progressPercent>=90 ? 90 : progressPercent; 
	}
	onMounted(async () => {
		userMain()
		const tableHeight = totalHeight.value.offsetHeight
		tbodyHeight.value = tableHeight
	})
</script>

<style lang="scss">
	.user-manage {
		width: 100%;
		height: calc(100%);
		overflow: hidden;
		background: #efedee;
		padding: 10px 10px 0 10px;
		box-sizing: border-box;

		.community-input {
			width: 100%;
			height: 50px;
			display: flex;
			justify-content: space-between;
			align-items: center;

			button {
				width: 120px;
				height: 35px;
				display: block;
				text-align: center;
				line-height: 35px;
				font-size: 13px;
				border: 1px;
				background-color: rgb(249, 171, 8);
				color: white;
				border-radius: 6px;
				cursor: pointer;

				.el-upload {
					width: 100%;
					height: 100%;

					img {
						width: 100%;
						height: 100%;
						object-fit: cover;
					}
				}
			}

		}

		.avatar-uploader {
			width: 120px;
			height: 60px;
			display: block;
			text-align: center;
			line-height: 60px;
			font-size: 13px;
			border: 1px;
			color: #8c939d;
			overflow: hidden;
			border: 1px dashed #d9d9d9;
			border-radius: 6px;
			cursor: pointer;

			.el-upload {
				width: 100%;
				height: 100%;

				img {
					width: 100%;
					height: 100%;
					object-fit: cover;
				}
			}
		}
		.progress-value{
			margin-left: 10px;
			font-size: 16px;
			font-weight: bold;
			width: 180px;
			height: 60px;
			display: block;
			text-align: center;
			line-height: 60px;
			font-size: 12px;
			border: 1px;
			color: #f9ab08;
			overflow: hidden;
			border: 1px dashed #d9d9d9;
			border-radius: 6px;
			cursor: pointer;
		}
		.file-dec {
			display: block;
			width: 100%;
			margin-left: 10px;
			color: red;
			font-size: 12px;
			height: 35px;
			line-height: 35px;
		}

		.user-manage-table {
			width: 100%;
			height: calc(100% - 50px - 40px);
		}

		.user-page {
			width: 100%;
			height: 40px;
			display: flex;
			justify-content: space-between;
			padding: 0 20px;
			box-sizing: border-box;
			align-items: center;

			h1 {
				color: #9195a1;
				font-size: 15px;
				letter-spacing: 2px;
				font-weight: 500;
			}

			.user-operation-button {
				display: flex;
				justify-content: flex-end;
				height: 50px;
				margin-top: 0;
				margin-bottom: 10px;

				button {
					background: white;
					border: 1px solid #ccc;
					color: var(--main-font-color);
					border-right: 0 !important;
					font-size: 13px;
				}

				li {
					background: white;
					border: 1px solid #ccc;
					color: var(--main-font-color);
					font-size: 13px;
					border-radius: 0;
				}

				.el-pagination.is-background .el-pager li:not(.disabled).active {
					background: rgb(59, 115, 240);
					border: 1px solid rgb(59, 115, 240);
				}

				.el-pagination.is-background .btn-next,
				.el-pagination.is-background .btn-prev,
				.el-pagination.is-background .el-pager li {
					margin: 0;
					border-right: 0;
					width: 30px !important;
					height: 30px !important;
				}

				.el-pagination.is-background .btn-next:disabled,
				.el-pagination.is-background .btn-prev:disabled {
					background: white;
				}

				.btn-next {
					border-right: 1px solid #ccc !important;
				}

			}
		}
	}
</style>
